package com.spring.handler;

import com.spring.http.Request;
import com.spring.http.Response;
import com.spring.http.Servlet;
import com.spring.server.KingService;

import java.io.InputStream;
import java.net.Socket;

/**
 * @author Spring King
 * @date 2021/7/10
 */
public class RequestProcessor extends Thread {

    private final Socket socket;

    private final KingService service;

    public RequestProcessor(Socket socket, KingService service) {
        this.socket = socket;
        this.service = service;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            Servlet servlet = service.getServlet(request);
            if (servlet == null) {
                response.outputHtml(request.getUrl());
            } else {
                servlet.service(request, response);
            }
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
